package websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

import java.io.IOException;

@WebSocket
public class TalkWithUserHandler {

    @OnWebSocketConnect
    public void connected(Session session) {
        TalkWithServerHandler.userMap.put(session, "User" + TalkWithServerHandler.userId++);
    }

    @OnWebSocketClose
    public void closed(Session session, int statusCode, String reason) {
        TalkWithServerHandler.userMap.remove(session);
    }

    /**
     * 点对点用户之间通信
     *      通信格式：int||String
     *              int：用户ID
     *              ||：用户ID与要发送的信息之间的分隔
     *              String：要发送的信息
     *            例：1||message
     *
     * @param session
     * @param message
     */
    @OnWebSocketMessage
    public void message(Session session, String message) {
        try {
            String userStr = TalkWithServerHandler.userMap.get(session);
            System.out.println("User: " + userStr);
            System.out.println("Message: " + message);

            int index = message.indexOf("||");
            if (index != -1) {
                // 获取要与之通信的用户ID
                String targetUser = "User" + message.substring(0, index);
                // 获取用户发送的消息
                String messageInfo = message.substring(index + 2);
                for (Session session1 : TalkWithServerHandler.userMap.keySet()) {
                    if (TalkWithServerHandler.userMap.get(session1).equals(targetUser)) {
                        // 向要与之通信的用户发送消息
                        session1.getRemote().sendString("【" + userStr + "】发来信息：" + messageInfo);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
